<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="岗位名称" prop="postName">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['talent:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['talent:template:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="岗位ID" align="center" prop="postId" />
      <el-table-column label="岗位编码" align="center" prop="postCode" />
      <el-table-column label="岗位名称" align="center" prop="postName" />
      <el-table-column label="模板表名" align="center" prop="tableName" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['talent:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleFieldManage(scope.row)"
            v-hasPermi="['talent:template:field']"
          >模版管理</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['talent:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人才库模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位" prop="postId">
          <el-select v-model="form.postId" placeholder="请选择岗位" @change="handlePostChange">
            <el-option
              v-for="post in postList"
              :key="post.postId"
              :label="post.postName"
              :value="post.postId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 字段管理对话框 -->
    <el-dialog title="字段管理" :visible.sync="fieldDialogOpen" width="800px" append-to-body>
      <div style="margin-bottom: 10px;">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddField">新增字段</el-button>
      </div>
      <el-table :data="fieldList" border>
        <el-table-column label="字段名（英文）" prop="fieldName" width="150">
          <template slot-scope="scope">
            <el-input v-if="scope.row.editing" v-model="scope.row.fieldName" size="small" />
            <span v-else>{{ scope.row.fieldName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字段显示名称" prop="fieldLabel" width="150">
          <template slot-scope="scope">
            <el-input v-if="scope.row.editing" v-model="scope.row.fieldLabel" size="small" />
            <span v-else>{{ scope.row.fieldLabel }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字段类型" prop="fieldType" width="120">
          <template slot-scope="scope">
            <el-select v-if="scope.row.editing" v-model="scope.row.fieldType" size="small">
              <el-option label="文本" value="varchar" />
              <el-option label="整数" value="int" />
              <el-option label="长整数" value="bigint" />
              <el-option label="日期时间" value="datetime" />
            </el-select>
            <span v-else>{{ scope.row.fieldType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字段长度" prop="fieldLength" width="100">
          <template slot-scope="scope">
            <el-input-number v-if="scope.row.editing" v-model="scope.row.fieldLength" size="small" :min="1" :max="500" />
            <span v-else>{{ scope.row.fieldLength }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sortOrder" width="80">
          <template slot-scope="scope">
            <el-input-number v-if="scope.row.editing" v-model="scope.row.sortOrder" size="small" :min="0" />
            <span v-else>{{ scope.row.sortOrder }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="scope.row.editing" size="mini" type="text" @click="handleSaveField(scope.row, scope.$index)">保存</el-button>
            <el-button v-if="scope.row.editing" size="mini" type="text" @click="handleCancelField(scope.$index)">取消</el-button>
            <el-button v-if="!scope.row.editing" size="mini" type="text" @click="handleEditField(scope.row)">编辑</el-button>
            <el-button v-if="!scope.row.editing" size="mini" type="text" @click="handleDeleteField(scope.row, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fieldDialogOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, addTemplate, updateTemplate, delTemplate, getTemplateFields, saveTemplateFields, delTemplateField } from "@/api/talent/template";
import { listPost } from "@/api/system/post";

export default {
  name: "TalentTemplate",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人才库模板表格数据
      templateList: [],
      // 岗位列表
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 字段管理对话框
      fieldDialogOpen: false,
      // 字段列表
      fieldList: [],
      // 当前模板ID
      currentTemplateId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postId: [
          { required: true, message: "岗位不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getPostList();
  },
  methods: {
    // 打开内部标签页
    openInnerTab(title, path, id, query) {
      // 唯一路径使用 id：例如 /talent/templateField/fields/123
      const routePath = path.endsWith('/') ? path + id : path + '/' + id
      const fullPath = this.$router.resolve({ path: routePath, query }).route.fullPath
      // 如果已存在相同 fullPath 的标签，则直接切换
      const exists = this.$store.state.tagsView.visitedViews.some(v => v.fullPath === fullPath)
      if (exists) {
        this.$router.push({ path: routePath, query })
        return
      }
      // 不存在则添加新标签并跳转
      const routeObj = { path: routePath, query: query, meta: { title: title } }
      this.$store.dispatch('tagsView/addView', routeObj)
      this.$router.push(routeObj)
    },
    /** 查询人才库模板列表 */
    getList() {
      this.loading = true;
      console.log('开始加载人才库模板列表...', this.queryParams);
      listTemplate(this.queryParams).then(response => {
        console.log('加载成功:', response);
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('加载失败:', error);
        this.$modal.msgError('加载人才库模板列表失败');
        this.loading = false;
      });
    },
    /** 查询岗位列表 */
    getPostList() {
      listPost().then(response => {
        this.postList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        postId: null,
        postCode: null,
        postName: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人才库模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改人才库模板";
      });
    },
    /** 岗位变化 */
    handlePostChange(postId) {
      const post = this.postList.find(p => p.postId === postId);
      if (post) {
        this.form.postCode = post.postCode;
        this.form.postName = post.postName;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除人才库模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 字段管理 */
    handleFieldManage(row) {
      // 在当前页面内的 TagsView 新开一个页签
      const title = `【${row.postName}】模版设置`
      this.openInnerTab(title, '/talent/templateField/fields', row.id, { id: row.id })
    }
  }
};
</script>

